package com.may.wind.service;

import com.may.wind.dao.UserRepository;
import com.may.wind.entity.User;
import com.may.wind.pojo.Register;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService implements UserDetailsService {
    @Autowired
    UserRepository userRepository;

    @Autowired
    RoleService roleService;

    @Autowired
    UserRoleService userRoleService;

    /**
     * 密码加密(strength=24 设置加密强度4-31)
     *
     * @return
     */
    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        return user;
    }

    public List<User> finaAll() {
        List<User> users = userRepository.findAll();
        return users;
    }

    public boolean isExist(String username) {
        User user = userRepository.findByUsername(username);
        return null != user;
    }

    public Map<String, Object> register(Register register) {
        String username = register.getUsername();
        String name = register.getName();
        String phone = register.getPhone();
        String email = register.getEmail();
        String password = register.getPassword();

        User user = new User();
        // 对 html 标签进行转义，防止 XSS 攻击
        username = HtmlUtils.htmlEscape(username);
        user.setUsername(username);
        password = HtmlUtils.htmlEscape(password);
        name = HtmlUtils.htmlEscape(name);
        user.setName(name);
        phone = HtmlUtils.htmlEscape(phone);
        user.setPhone(phone);
        email = HtmlUtils.htmlEscape(email);
        user.setEmail(email);
        user.setEnabled(true);

        Map<String, Object> message = new HashMap<>();
        if (isExist(username)) {
            message.put("success", false);
            message.put("message", "已存在该用户！");
            return message;
        }
        user.setPassword(passwordEncoder.encode(password));
        try {
            userRepository.save(user);
            message.put("success", true);
            message.put("message", "添加成功！");
        } catch (Exception exception) {
            exception.printStackTrace();
            message.put("success", false);
            message.put("message", exception.getMessage());
        }
        return message;
    }

    public void updateUserStatus(User user) {
        User userInDB = userRepository.findByUsername(user.getUsername());
        userInDB.setEnabled(user.isEnabled());
        userRepository.save(userInDB);
    }

    public User resetPassword(User user) {
        User userInDB = userRepository.findByUsername(user.getUsername());
        String password = user.getPassword();
        password = HtmlUtils.htmlEscape(password);
        userInDB.setPassword(passwordEncoder.encode(password));
        return userRepository.save(userInDB);
    }

    public void editUser(User user) {
        User userInDB = userRepository.findByUsername(user.getUsername());
        userInDB.setName(user.getName());
        userInDB.setPhone(user.getPhone());
        userInDB.setEmail(user.getEmail());
        userRepository.save(userInDB);
        userRoleService.saveRoleChanges(userInDB.getId(), user.getRoles());
    }

    public void deleteById(long userId) {
        userRepository.deleteById(userId);
    }
}
